package com.study.elasticsearchstudy.entity;

import lombok.Data;
import lombok.experimental.Accessors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 响应对象
 *
 * @author
 * @since 1.0.0
 */
@Data
@Accessors(chain = true)
public class MyResponse {
    private Object data;
    private String message;
    private int code;
    private boolean success;

    private static final Logger LOGGER = LoggerFactory.getLogger(MyResponse.class);

    public static MyResponse success() {
        MyResponse myResponse = new MyResponse();
        myResponse.setSuccess(true);
        myResponse.setCode(200);
        return myResponse;
    }

    public static MyResponse success(Object data) {
        MyResponse myResponse = new MyResponse();
        myResponse.setSuccess(true);
        myResponse.setCode(200);
        myResponse.setData(data);
        if (data instanceof String) {
            myResponse.setMessage((String) data);
        }
        return myResponse;
    }

    public static MyResponse success(Object data, String message) {
        MyResponse myResponse = new MyResponse();
        myResponse.setSuccess(true);
        myResponse.setCode(200);
        myResponse.setData(data);
        myResponse.setMessage(message);
        return myResponse;
    }

    public static MyResponse failure() {
        MyResponse myResponse = new MyResponse();
        myResponse.setSuccess(false);
        myResponse.setCode(500);
        return myResponse;
    }

    public static MyResponse failure(Object data) {
        MyResponse myResponse = new MyResponse();
        myResponse.setSuccess(false);
        myResponse.setCode(500);
        myResponse.setData(data);
        if (data instanceof String) {
            myResponse.setMessage((String) data);
        }
        return myResponse;
    }

    public static MyResponse failure(Object data, String message) {
        MyResponse myResponse = new MyResponse();
        myResponse.setSuccess(false);
        myResponse.setCode(500);
        myResponse.setData(data);
        myResponse.setMessage(message);
        return myResponse;
    }

    public MyResponse put(String key, Object value) {
        if (data == null) {
            data = new HashMap<String, Object>();
        }
        try {
            ((Map) data).put(key, value);
        } catch (Exception e) {
            LOGGER.error("返回结果时出错,data的类型为:" + data.getClass().getName() + ",不能强转为Map");
        }
        return this;
    }

}
